import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/home',
      name: 'home',
      component: () => import('@/views/Home.vue'),
    },
    {
      path: '/',
      name: 'login',
      component: () => import('@/views/Login.vue'),
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('@/views/Register.vue')
    },
    {
      path: '/forgetpassword',
      name: 'forgetpassword',
      component: () => import('@/views/ForgetPassword.vue')
    },
    {
      path: '/verification-login',
      name: 'verification-login',
      component: () => import('@/views/VerificationLogin.vue') 
    },
    {
      path:'/UserEdit/:id',
      component:()=>import('@/components/UserCeateOrEdit.vue')
    }
  ],
});

//路由守护
router.beforeEach((to, from, next) => {
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth); // 检查目标路由是否需要认证
  const token = localStorage.getItem('token'); // 从本地存储获取 JWT

  if (requiresAuth && !token) {
    next('/'); // 如果需要认证但没有 token，跳转到登录页面
  } else {
    next(); // 否则正常跳转
  }
})

export default router
